import requests
import time
import json
from bs4 import BeautifulSoup
from utils.RedisUtils import redis_client

# 获取头条热榜新闻
def parse_toutiao_hot():
    print("获取头条热榜新闻")
    url = "https://www.toutiao.com/hot-event/hot-board/?origin=toutiao_pc"
    # 接口获取数据
    response = requests.get(url)
    result = []
    data = response.json()
    for item in data["data"]:
        hot_value = item["HotValue"]
        hot_url = item["Url"]
        hot_label = item["Title"]
        result.append({
            "hot_value": hot_value,
            "hot_url": hot_url,
            "hot_label": hot_label
        })
    return result

# 获取百度热榜新闻
def parse_baidu_hot():
    print("获取百度热榜新闻")
    url = "https://top.baidu.com/board?tab=realtime"
    response = requests.get(url)
    # 解析页面
    soup = BeautifulSoup(response.text, "html.parser")
    div_ = soup.find_all("div", class_="category-wrap_iQLoo horizontal_1eKyQ")
    result = []
    for item in div_:
        value = item.find(class_='hot-index_1Bl1a').text
        link = item.find(class_='title_dIF3B').get('href')
        title = item.find(class_='c-single-text-ellipsis').text
        result.append({
            "hot_value": value,
            "hot_url": link,
            "hot_label": title
        })
    return result

# 获取热点信息
async def getHotData(name: str, item_id: str):
    cache_key = f"rank_{item_id}"
    try:
        # 从redis里获取数据
        cached_data = await redis_client.get(cache_key)
        if cached_data:
            return json.loads(cached_data)
    except Exception as e:
        # redis获取数据失败
        print(f"Redis获取数据失败：{e}")
    latest_record = ""
    if item_id == "toutiao":
        latest_record = parse_toutiao_hot()
    elif item_id == "baidu":
        latest_record = parse_baidu_hot()

    try:
        await redis_client.setex(cache_key, 3600, json.dumps(latest_record))
        return {
            "name": name,
            "data": latest_record,
            "time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        }
    except Exception as e:
        # 处理异常
        print(f"服务异常：{e}")
        raise Exception(status_code=500, detail="内部服务异常")

# 测试
if __name__ == "__main__":
    parse_baidu_hot()